package com.bill.concurrency.times;


import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * SimpleDateFormat是线程不安全的。
 * @author bill
 */
@Slf4j
public class DateFormatExample3 {
    private static int clientTotal=5000;
    private static int threadTotal=200;
    private static DateTimeFormatter formatter=DateTimeFormat.forPattern("yyyyMMdd");

    public static void main(String[] args) {
        final ExecutorService executorService=Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
        final Semaphore semaphore=new Semaphore(threadTotal);
        for(int i=0;i<clientTotal;i++){
            final int curNum=i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    formatDate(curNum);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("error:{}",e);
                }
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("error:{}",e);
        }

        log.info("5000次调用全部完成");

    }

    private static void formatDate(int i){
        log.info("当前序号{}--->{}",i,DateTime.parse("20180507",formatter).toDate());
    }
}
